var Admin = require("../models/admin");
var crypto = require("../util/crypto");
var Article = require("../models/article");
var Navigator = require("../models/navigator");
var Category = require("../models/category");
var Page = require("../models/page");
var Banner = require("../models/banner");
var Message = require("../models/message");
var Comment = require("../models/comment");
var Cases = require("../models/cases");
var Friendlylinks = require("../models/friendlylinks");
var secret = "admin";

exports.login = function (req, res) {
	var _admin = req.body;
	_admin.password = crypto.encrypt(_admin.password, secret);
	//5ff9eae5f723a3c19c0addf3830374ae
	_admin = new Admin(_admin);
	_admin.login(function (err, admin) {
		if (admin) {
			req.session.admin = admin;
			res.send({"success": true,"msg": "登录成功"});
		} else {
			res.send({"success": false,"msg": "用户密码错误"});
		}
	});
}
exports.editPassword = function (req, res) {
	var _admin = req.body;
	var username = req.session.admin.username;
	_admin.password = crypto.encrypt(_admin.password, secret);
	Admin.update({"username":username},{$set:{"password":_admin.password}}, function (err) {
		if (!err) {
			res.send({"success": true,"msg": "修改成功"});
		} else {
			res.send({"success": false,"msg": "修改失败"});
		}
	});
}

exports.showSignin = function (req, res) {
	res.render('admin/login', {
		title: '登录页面'
	})
}

exports.main = function (req, res) {
	var admin = req.session.admin;
	res.render("admin/main", {
		title: '后台管理系统',
		admin: admin
	});
}

exports.isLogin = function (req, res, next) {
	var admin = req.session.admin;
	if (!admin) {
		return res.redirect("/admin/login");
	}
	next();
}

exports.quit = function (req, res) {
	req.session.admin = null;
	res.redirect("/admin/login");
}
//批量删除公共方法
exports.baseDelete = function (req, res) {
	var bodyDate = req.body;
	var deleteDate= function ($this) {
		$this.remove({_id: {$in:bodyDate['idArr[]']}}, function (err) {
			if(err){
				res.send({"success":false,"msg":"删除失败"});
			}else{
				res.send({"success":true,"msg":"删除成功"});
			}
		})
	}
	switch (bodyDate.action){
		case "banner":
			deleteDate(Banner)
			break;
		case "article":
			deleteDate(Article)
			break;
		case "cases":
			deleteDate(Cases)
			break;
		case "category":
			deleteDate(Category)
			break;
		case "message":
			deleteDate(Message)
			break;
		case "navigator":
			deleteDate(Navigator)
			break;
		case "links":
			deleteDate(Friendlylinks)
			break;
        case "comment":
            deleteDate(Comment)
            break;
		case "page":
			deleteDate(Page)
			break;
	}

}